import {createSlice} from "@reduxjs/toolkit";
import {deleteWeibo, getWeibo, postWeibo, putWeibo} from "../../api/weibo";
import {useSelector} from "_react-redux@8.0.2@react-redux";

const weiboSlice = createSlice({
    name:"weibo",
    initialState:{
        contentList:[],// 微博列表
        pageNo:1,
        pageSum:1,
        pageSize:30
    },
    reducers:{
        upContentList(state,{payload}){
            state.contentList = payload;
        },
        upWeiboState(state,{payload}){
            state.contentList = payload.contentList;
            state.pageNo = payload.pageNo;
            state.pageSum = payload.pageSum;
            state.pageSize = payload.pageSize;
        }
    }
})
export const {upContentList,upWeiboState} = weiboSlice.actions;
// 获取微博
export  const getWeiboAsync = (pageNo,pageSize)=>{
    return async (dispatch,getState)=>{
        if(!pageNo) pageNo = getState().weibo.pageNo;
        if(!pageSize) pageSize = getState().weibo.pageSize;
        const result = await getWeibo(pageNo,pageSize);

        dispatch(upWeiboState({
           ...result,
            pageSize
        }));
    }
}
// 添加微博
export const postWeiboAsync = (contentRef)=>{
    return async (dispatch)=>{
        const content = contentRef.current.value.trim();
        if(content.length === 0){
            alert("请输入微博内容");
            return;
        }
        await postWeibo(content);
        contentRef.current.value = null;
        dispatch(getWeiboAsync())
    }
}
// 删除微博
export const deleteWeiboAsync = (id)=>{
    return async dispatch =>{
        await deleteWeibo(id);
        dispatch(getWeiboAsync());
    }
}
// 修改微博
export const putWeiboAsync = (id,type)=>{
    return async (dispatch,getState) =>{
        await putWeibo(id,type);
        dispatch(getWeiboAsync());
        // console.log("111111",getState());
        // const {pageNo,pageSize} = getState().weibo;
        // await putWeibo(id,type);
        // console.log(2222,pageNo,pageSize);
        // dispatch(getWeiboAsync(pageNo,pageSize));
    }
}







// 返回该模块的数据状态
export const useSelectorWeibo = ()=>{
    return  useSelector((state)=>{
        return state.weibo;
    });
}

export default weiboSlice.reducer;